﻿using System;
using System.Collections.Generic;
using Eg.Core;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.SqlCommand;

namespace UsingCriteriaQueries {

  public class Queries {

    private readonly ISession _session;

    public Queries(ISession session) {
      if (session == null)
        throw new ArgumentNullException("session");
      _session = session;
    }

    public IEnumerable<Movie> GetMoviesDirectedBy(string directorName)
    {
        return _session
            .CreateCriteria<Movie>()
            .Add(Restrictions.Eq("Director", directorName))
            .List<Movie>();
    }

    public IEnumerable<Movie> GetMoviesWith(string actorName)
    {
        return _session
            .CreateCriteria<Movie>()
            // inner join between Movies and ActorRoles based on the contents of a Movie's Actors collection
            .CreateCriteria("Actors", JoinType.InnerJoin)
            // context is changed - from Movie to ActorRole
            .Add(Restrictions.Eq("Actor", actorName))  // <-- filters ActorRole, because of join also filters Movies
            .List<Movie>();
    }

    public Book GetBookByISBN(string isbn)
    {
        return _session
            .CreateCriteria<Book>()
            .Add(Restrictions.Eq("ISBN", isbn))
            .UniqueResult<Book>();
    }

    public IEnumerable<Product> GetProductByPrice(decimal minPrice, decimal maxPrice)
    {
        return _session
            .CreateCriteria<Product>()
            .Add(Restrictions.And(Restrictions.Ge("UnitPrice", minPrice), Restrictions.Le("UnitPrice", maxPrice)))
            .AddOrder(Order.Asc("UnitPrice"))
            .List<Product>();
    }
  
  
  }

}
